package com.cn.wanxi.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")///*代表拦截所有路径
public class Filter implements javax.servlet.Filter {
    /**
     * servlet的声明周期
     * 被创建
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 如果我们这里不做任何代码的编写，那么就不会进行跳转，没有放行
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        0.乱码
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");//请求编码格式为utf-8
        resp.setCharacterEncoding("UTF-8");//响应编码格式为utf-8
        resp.setContentType("text/json;charset=utf-8");//解决传值乱码

        //判断该用户是否已经登录，如果没有登录，则返回登录页面，否则，直接放行
        //我们需要有几个页面进行放行，登录页面和注册页面不需要进行拦截/back/login.jsp /back/register.jsp
        String url = req.getServletPath();
//        req.getRequestURI();///http://localhost:8080/back/login.jsp
        System.out.println(url);
        //判断路径
        String[] urls = {"/back/login.jsp", "/back/register.jsp", "/code", "/login", "/UserAdd"};
        boolean fangxing = false;
        for (String ur : urls) {
            if (url.equals(ur)) {
                fangxing = true;
                break;
            }
        }
        //判断文件后缀，如果是我们数组里面的就放行
        String[] urlb = {"img", "js", "css"};
//        String[] urlValue = url.split(".");
//        String aa = urlValue[1];//将所有img，js，css进行放行
        for (String bb : urlb) {
            if (url.endsWith(bb)) {
                fangxing = true;
                break;
            }
        }

        if (fangxing) {
            filterChain.doFilter(req, resp);//放行
        } else {
            Object username = req.getSession().getAttribute("username");
            if (username == null) {//如果在session里面取得的用户名为空，则表示需要重新登录
                resp.sendRedirect("/back/login.jsp");
            } else {
                filterChain.doFilter(req, resp);//放行
            }
        }
    }

    /**
     * 被销毁
     */
    @Override
    public void destroy() {

    }
}
